<template>
  <article class="view" @mouseup="scrollPageTab('up', $event)" draggable="false">
    <header>
      <div class="logo" @click="pageTurn('/')">
        <!-- <img :src="require('assets/top-nav-left-logo.png')" alt="" /> -->
        <p>资源管理平台</p>
      </div>
      <el-dropdown @command="handleCommand">
        <div class="avatar">
          <img :src="require('assets/img/avatar.png')" alt="" />
          <span>{{ token.username }}</span>
          <i class="el-icon-caret-bottom"></i>
        </div>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item icon="el-icon-lock" command="resetPassword"> 修改密码 </el-dropdown-item>
          <el-dropdown-item class="signOut" icon="el-icon-switch-button" command="signOut"> 安全退出 </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </header>
    <section class="menuWithViewport">
      <div :class="screenData == 'small' ? 'smallMenu' : 'bigMenu'">
        <div class="menuTrigger" @click="showMenu = !showMenu">
          <i class="el-icon-arrow-left" :class="showMenu ? 'el-icon-caret-left' : 'el-icon-caret-right'"></i>
        </div>
        <div>
          <div class="sideBar">
            <div v-for="(parent, fi) in authorityTree" :key="fi">
              <el-popover v-show="!showMenu" width="180" trigger="hover" placement="right-start">
                <ul
                  v-if="parent.children && parent.children.length"
                  :class="{
                    childWrap: true,
                    displayNone: parentIndex !== fi,
                  }"
                >
                  <li
                    v-for="(children, ci) in parent.children"
                    :key="ci"
                    v-show="children.type - 0 === 1"
                    :class="{ active: childIndex === `${fi}-${ci}` }"
                    :ref="`${fi}-${ci}--popover`"
                    @click="menuItemClickTwo(children, `${fi}-${ci}--popover`, 'popover')"
                  >
                    <x-svg-icon :iconName="children.icon || ''" :className="iconClassName(`${fi}-${ci}`)" />
                    <p>{{ children.permission_name }}</p>
                  </li>
                </ul>
                <p
                  v-else
                  class="popoverTitle"
                  @click.stop="menuClick(parent.route_path, fi, 'popoverTitle', parent.route_name)"
                >
                  {{ parent.permission_name }}
                </p>
                <div
                  slot="reference"
                  :class="{ sideBarItem: true, active: parentIndex - 0 === fi }"
                  @click.stop="menuClick(parent.route_path, fi, '', parent.route_name)"
                >
                  <x-svg-icon :iconName="parent.icon || ''" className="iconClass" />
                </div>
              </el-popover>
              <!-- 左边图标 -->
              <div
                v-show="showMenu"
                slot="reference"
                :class="{ sideBarItem: true, active: parentIndex - 0 === fi }"
                @click.stop="menuClick(parent.route_path, fi, '', parent.route_name)"
              >
                <x-svg-icon :iconName="parent.icon || ''" className="iconClass" />
              </div>
            </div>
          </div>
          <div class="sideMenu" ref="sideMenu">
            <ul>
              <li v-for="(parent, fi) in authorityTree" :key="fi" v-show="parent.type - 0 === 1">
                <p
                  :class="{ outerActive: outerActiveIndex == fi }"
                  @click.stop="menuClick(parent.route_path, fi, 'toggle', parent.route_name)"
                >
                  <span>{{ parent.permission_name }}</span>
                  <i
                    v-if="parent.children && parent.children.length"
                    :class="{
                      'el-icon-arrow-right': true,
                      active: parentIndex === fi,
                    }"
                  />
                </p>
                <ul
                  v-if="parent.children && parent.children.length"
                  :class="{
                    childWrap: true,
                    menuHidden: parentIndex !== fi,
                  }"
                >
                  <li
                    v-for="(children, ci) in parent.children"
                    :key="ci"
                    v-show="children.type - 0 === 1"
                    :class="{ active: childIndex === `${fi}-${ci}` }"
                    :ref="`${fi}-${ci}`"
                    @click="menuItemClick(children, `${fi}-${ci}`)"
                  >
                    <x-svg-icon :iconName="children.icon || ''" :className="iconClassName(`${fi}-${ci}`)" />
                    <!-- 侧边栏 -->
                    <p>{{ children.permission_name }}</p>
                  </li>
                </ul>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <section class="viewport" ref="viewport">
        <header class="pageTabs" draggable="false">
          <div
            ref="pageTabWrap"
            class="pageTabWrap"
            @mousedown.stop="scrollPageTab('down', $event)"
            @mousemove.stop="scrollPageTab('move', $event)"
            draggable="false"
          >
            <!-- action === 'refresh' -->
            <ul draggable="false">
              <li
                draggable="false"
                v-for="(item, i) in pageTabs"
                :key="i"
                :class="item.title === currentPageTitle && 'active'"
                @click="pageTurn(item.path, item.query, 'refresh')"
              >
                <span class="title_class_el"> {{ item.title }}</span>
                <i class="el-icon-error" v-show="i !== 0" @click.stop="deleteTab(i, item.title)"></i>
              </li>
              <li></li>
            </ul>
          </div>
          <div class="actions">
            <el-dropdown class="elDropdown" trigger="click" @command="handlePageTab">
              <div>
                <span></span>
                <i class="el-icon-arrow-down"></i>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="(item, i) in pageTabActions" :key="i" :command="item.value">
                  <div class="dropdownContent">
                    <img :src="item.icon" alt="" />
                    <span>{{ item.label }}</span>
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </header>
        <main>
          <div style="background-color: #ffffff; padding-top: 0px; position: relative; min-height: calc(100vh - 144px)">
            <!-- <x-loading /> -->
            <keep-alive>
              <router-view />
            </keep-alive>
          </div>
          <footer>
            <p @click="websiteBtn" style="cursor: pointer">©2025-2028 版权所有 技术支持： 成都贝图科技有限公司</p>
          </footer>
        </main>
      </section>
    </section>

    <!-- 对话框 -->
    <x-dialog
      :visible="dialogVisible"
      dangerBtnText="确认"
      infoBtnText="取消"
      @cancel="dialogCancel"
      @confirm="dialogConfirm"
    >
      <div class="dialogContent" v-if="dialogType === 'resetPassword'">
        <x-svg-icon iconName="dialogCaution" className="iconClass"> </x-svg-icon>
        <p>修改密码</p>
        <el-form ref="elForm" :model="formData" size="mini" :rules="rules">
          <el-form-item label="新密码" prop="password">
            <el-input
              type="password"
              clearable
              show-password
              placeholder="请输入新密码"
              autocomplete="off"
              v-model="formData.password"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirm_password">
            <el-input
              type="password"
              clearable
              show-password
              autocomplete="off"
              placeholder="请输入新密码"
              v-model="formData.confirm_password"
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="dialogContent" v-if="dialogType === 'signOut'">
        <x-svg-icon iconName="dialogCaution" className="iconClass"> </x-svg-icon>
        <p>确定退出登录吗？</p>
      </div>
    </x-dialog>
    <x-dialog
      :visible="resetPasswordVisible"
      dangerBtnText="确认"
      infoBtnText="取消"
      @cancel="resetPasswordCancel"
      @confirm="handleCommand('resetPassword')"
    >
      <div class="dialogContent">
        <x-svg-icon iconName="dialogCaution" className="iconClass"> </x-svg-icon>
        <p>当前密码为系统初始密码,为了您的账号安全,请先修改密码！</p>
      </div>
    </x-dialog>
  </article>
</template>

<script>
import Vue from "vue"
import GrandsonMenu from "./components/grandsonMenu/index.vue"
export default {
  components: {},
  data() {
    return {
      outerActiveIndex: "",
      system_unit_name: "",

      offsetValue: false,
      dialogType: "",
      dialogVisible: false,
      formData: {
        token: "",
        password: "",
        confirm_password: "",
      },
      resetPasswordVisible: false,
      rules: {
        password: [
          {
            required: true,
            validator: this.$elValidator?.password,
            trigger: "blur",
          },
        ],
        confirm_password: [
          {
            required: true,
            validator: this.validatorPassword2,
            trigger: "blur",
          },
        ],
      },
      showMenu: true,
      parentIndex: "",
      childIndex: "",
      pageTabActions: [
        {
          label: "重新加载当前页",
          value: "reload",
          icon: require("assets/img/pageTab-reload.png"),
        },
        {
          label: "关闭当前标签页",
          value: "closeCurrent",
          icon: require("assets/img/pageTab-close.png"),
        },
        {
          label: "关闭左边标签页",
          value: "closeLeft",
          icon: require("assets/img/pageTab-closeLeft.png"),
        },
        {
          label: "关闭右边标签页",
          value: "closeRight",
          icon: require("assets/img/pageTab-closeRight.png"),
        },
        {
          label: "关闭其他标签页",
          value: "closeOther",
          icon: require("assets/img/pageTab-closeOther.png"),
        },
        {
          label: "关闭全部标签页",
          value: "closeAll",
          icon: require("assets/img/pageTab-closeAll.png"),
        },
      ],
      screenData: "",
    }
  },
  created() {
    this.screenData = localStorage.getItem("screen")
    if (this.ismodifypwd) this.resetPasswordVisible = true
    this.system_unit_name = localStorage.getItem("system_unit_name")
  },
  computed: {
    token() {
      let obj = localStorage.getItem("read_token") || "{}"
      return JSON.parse(obj)
    },
    authorityTree() {
      let arr = localStorage.getItem("authorityTree")
      return arr && JSON.parse(arr)
    },
    pageTabs() {
      return this.$store.state.pageTabState.pageTabs
    },
    currentPageTitle() {
      return this.$store.state.pageTabState.currentPageTitle
    },
    currentPageIndex() {
      return Number(this.$store.state.pageTabState.currentPageIndex)
    },
    ismodifypwd() {
      return JSON.parse(localStorage.getItem("ismodifypwd"))
    },
  },
  methods: {
    scrollPageTab(type, event) {
      let step = 5
      if (type === "down") {
        this.offsetValue = event.screenX
      } else if (type === "up") {
        this.offsetValue = false
      }
      if (this.offsetValue) {
        let pageTabWrap = this.$refs.pageTabWrap
        if (event.screenX - this.offsetValue < 0) {
          this.offsetValue = event.screenX
          pageTabWrap.scrollLeft += step
        }
        if (event.screenX - this.offsetValue > 0) {
          this.offsetValue = event.screenX
          pageTabWrap.scrollLeft -= step
        }
      }
    },

    validatorPassword2(rule, v, callback) {
      let reg = /[\w_-]{6,20}/
      if (v) {
        if (reg.test(v)) {
          v + "" === this.formData.password + "" ? callback() : callback(new Error("两次输入密码不一致!"))
        } else {
          callback(new Error("密码为6到20位数之间"))
        }
      } else {
        callback(new Error("请输入新密码"))
      }
    },
    handleCommand(type) {
      this.dialogType = type
      this.dialogVisible = true
      this.resetPasswordVisible = false
      this.formData = this.$options.data().formData
    },
    handlePageTab(type) {
      switch (type) {
        case "reload":
          this.$router.go(0)
          break
        case "closeCurrent":
          this.deleteTab(this.currentPageIndex, type)
          break
        case "closeLeft":
          this.sliceTab(this.currentPageIndex, "left")
          break
        case "closeRight":
          this.sliceTab(this.currentPageIndex + 1, "right")
          break
        case "closeOther":
          this.deleteOtherTab()
          break
        case "closeAll":
          this.deleteAllTab()
          break
      }
    },
    sliceTab(i, position) {
      if (i - 0 >= 1) {
        this.$store.commit("pageTabState/sliceTab", { i, position })
        this.pageTabs.forEach((item, i) => {
          if (item.title === this.currentPageTitle) {
            this.$store.commit("pageTabState/setCurrentPageIndex", i)
          }
        })
      }
    },
    deleteTab(i, title) {
      if (i - 0 >= 1) {
        this.$store.commit("pageTabState/deleteTab", i)
        this.pageTabs.forEach((item, i) => {
          if (item.title === this.currentPageTitle) {
            this.$store.commit("pageTabState/setCurrentPageIndex", i)
          }
        })
        if (title === "closeCurrent" || title === this.currentPageTitle) {
          let page = this.pageTabs[this.pageTabs.length - 1]
          this.pageTurn(page.path, page.query)
        }
      }
    },
    deleteAllTab() {
      this.$store.commit("pageTabState/deleteAllTab")
      this.$store.commit("pageTabState/setCurrentPageIndex", 0)
      let page = this.pageTabs[0]
      this.pageTurn(page.path, page.query)
    },
    deleteOtherTab() {
      this.$store.commit("pageTabState/deleteOtherTab", this.currentPageTitle)
      this.pageTabs.forEach((item, i) => {
        if (item.title === this.currentPageTitle) {
          this.$store.commit("pageTabState/setCurrentPageIndex", i)
        }
      })
    },
    //修改密码
    async dialogConfirm() {
      if (this.dialogType === "signOut") {
        localStorage.removeItem("read_token")
        localStorage.removeItem("authorityTree")
        sessionStorage.removeItem("read_token")
        localStorage.removeItem("libraryList")
        localStorage.removeItem("libraryList2")
        this.pageTurnParams("Login", { action: "refresh" })
      } else if (this.dialogType === "resetPassword") {
        await this.$refs?.elForm.validate()
        try {
          let res = await this.request({
            url: "/admin/manage/changeSelfPwd",
            method: "post",
            data: {
              token: "Bearer " + localStorage.getItem("read_token"),
              ...this.formData,
            },
          })
          this.dialogVisible = false
          this.$message({
            showClose: true,
            message: res.msg || "修改成功",
            type: "success",
          })
          localStorage.setItem("ismodifypwd", false)
          setTimeout(() => {
            localStorage.removeItem("authorityTree")
            localStorage.removeItem("libraryList")
            localStorage.removeItem("libraryList2")
            sessionStorage.removeItem("read_token")
            this.pageTurn("/login")
          }, 1000)
        } catch (err) {
          this.errorHandler(err)
        }
      }
    },
    dialogCancel() {
      this.dialogVisible = false
      if (this.dialogType === "resetPassword") {
        localStorage.setItem("ismodifypwd", false)
      }
    },
    resetPasswordCancel() {
      this.resetPasswordVisible = false
      localStorage.setItem("ismodifypwd", false)
    },
    iconClassName(i) {
      if (this.childIndex === i) {
        return "iconClass active"
      } else {
        return "iconClass"
      }
    },
    menuClick(path, i, type, pathname) {
      this.outerActiveIndex = i

      path && this.pageTurn(path)
      if (type === "popoverTitle") {
        this.parentIndex = i
      } else if (type === "toggle" && this.parentIndex === i) {
        this.parentIndex = ""
      } else {
        this.parentIndex = i
        this.showMenu = true
      }
    },
    menuItemClick(child, i, type) {
      this.childIndex = i
      if (type === "popover") {
        this.childIndex = i?.split("--")[0]
        this.parentIndex = i?.split("-")[0]
      }
      const el = document.getElementById("grandsonMenu")
      el?.remove()

      let grandson = child.children
      let path = child.route_path
      let pathname = child.route_name
      pathname && this.pageTurnParams(pathname, { action: "refresh" })
      //path && this.pageTurn(path)
      let haveMenu = false
      grandson?.forEach((item) => {
        if (item.type - 0 === 1) {
          haveMenu = true
        }
      })
      if (this.screenData == "small") {
        haveMenu && this.renderGrandsonSmall(grandson, i)
      } else {
        haveMenu && this.renderGrandsonMenu(grandson, i)
      }
    },
    renderGrandsonMenu(list, ref) {
      let i = ref.split("-")?.[1]
      // let remainder = (Number(i) + 1) % 2
      let remainder = (Number(i) + 1) % 3
      const grandsonMenuComp = Vue.extend(GrandsonMenu)
      let instance = new grandsonMenuComp({
        propsData: {
          list,
          remainder,
        },
      })
      const grandsonElement = instance.$mount().$el
      const targetElement = this.$refs[ref]?.[0]
      const parentElement = targetElement.parentElement
      let renderPosition = targetElement?.nextSibling
      if (remainder === 0) {
        parentElement.insertBefore(grandsonElement, renderPosition)
      } else if (remainder === 1) {
        renderPosition = renderPosition?.nextSibling
        let renderPositionOne = renderPosition?.nextSibling
        parentElement.insertBefore(grandsonElement, renderPositionOne)
      } else if (remainder === 2) {
        renderPosition = renderPosition?.nextSibling
        parentElement.insertBefore(grandsonElement, renderPosition)
      }
    },
    renderGrandsonSmall(list, ref) {
      let i = ref.split("-")?.[1]
      let remainder = (Number(i) + 1) % 2
      const grandsonMenuComp = Vue.extend(GrandsonMenu)
      let instance = new grandsonMenuComp({
        propsData: {
          list,
          remainder,
        },
      })
      const grandsonElement = instance.$mount().$el
      const targetElement = this.$refs[ref]?.[0]
      const parentElement = targetElement.parentElement
      let renderPosition = targetElement?.nextSibling
      if (remainder === 0) {
        parentElement.insertBefore(grandsonElement, renderPosition)
      } else if (remainder === 1) {
        renderPosition = renderPosition?.nextSibling
        parentElement.insertBefore(grandsonElement, renderPosition)
      }
    },
    menuItemClickTwo(child, i, type) {
      //  console.log(child)
      this.childIndex = i
      if (type === "popover") {
        this.childIndex = i?.split("--")[0]
        this.parentIndex = i?.split("-")[0]
      }
      const el = document.getElementById("grandsonMenu")
      el?.remove()

      let grandson = child.children
      let path = child.route_path
      let pathname = child.route_name
      pathname && this.pageTurnParams(pathname, { action: "refresh" })
      //path && this.pageTurn(path)
      let haveMenu = false
      grandson?.forEach((item) => {
        if (item.type - 0 === 1) {
          haveMenu = true
        }
      })
      haveMenu && this.renderGrandsonMenuTwo(grandson, i)
    },
    renderGrandsonMenuTwo(list, ref) {
      let i = ref.split("-")?.[1]
      let remainder = (Number(i) + 1) % 2
      const grandsonMenuComp = Vue.extend(GrandsonMenu)
      let instance = new grandsonMenuComp({
        propsData: {
          list,
          remainder,
        },
      })
      const grandsonElement = instance.$mount().$el
      const targetElement = this.$refs[ref]?.[0]
      const parentElement = targetElement.parentElement
      let renderPosition = targetElement?.nextSibling
      if (remainder === 0) {
        parentElement.insertBefore(grandsonElement, renderPosition)
      } else if (remainder === 1) {
        renderPosition = renderPosition?.nextSibling
        parentElement.insertBefore(grandsonElement, renderPosition)
      }
    },
    // 跳转官网
    websiteBtn() {
      window.open("http://www.cdbottle.com/")
    },
  },
  watch: {
    pageTabs: {
      deep: true,
      handler(val) {},
    },
    showMenu() {
      if (this.screenData == "small") {
        this.$refs.sideMenu.style.width = this.showMenu ? "180px" : "0px"
        this.$refs.viewport.style.width = this.showMenu ? "calc(100% - 240px)" : "calc(100% - 60px)"
      } else {
        this.$refs.sideMenu.style.width = this.showMenu ? "280px" : "0px"
        this.$refs.viewport.style.width = this.showMenu ? "calc(100% - 240px)" : "calc(100% - 60px)"
      }
    },
  },
}
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
